import { AxiosRequestConfig } from "../types";
import { isPlainObject, deepMerge } from "../helpers/util";


const strats = Object.create(null)

const stratKeysFromValue2 = ['url', 'params', 'data']

stratKeysFromValue2.forEach(key => {
    strats[key] = fromValue2Start
})

const stratKeysDeepMerge = ['headers']

stratKeysDeepMerge.forEach(key => {
    strats[key] = deepMergestrat
})

function defaultStrat(value1: any, value2: any): any {
    return typeof value2 !== 'undefined' ? value2 : value1
}

function fromValue2Start(value1: any, value2: any): any {
    if (typeof value2 !== 'undefined') {
        return value2
    }
}

function deepMergestrat(value1: any, value2: any): any {
    if (isPlainObject(value2)) {
        return deepMerge(value1, value2)
    } else if (typeof value2 !== 'undefined') {
        return value2
    } else if(isPlainObject(value1)) {
        return deepMerge(value1)
    } else if(typeof value1 !== 'undefined') {
        return value1
    }
}

export default function mergeConfig(config1: AxiosRequestConfig, config2?: AxiosRequestConfig): AxiosRequestConfig {
    if (!config2) {
        config2 = {}
    }

    const config = Object.create(null)

    for (const key in config2) {
        mergeField(key)
    }

    for (const key in config1) {
        if (!config2[key]) {
            mergeField(key)
        }
    }

    function mergeField(key: string): void {
        const strat = strats[key] || defaultStrat

        config[key] = strat(config1[key], config2![key])
    }

    return config

}
